/**
 * Copyright (c) 2013-2022 UChicago Argonne, LLC and The HDF Group.
 * Copyright (c) 2022-2024 Intel Corporation.
 * Copyright (c) 2024-2025 Hewlett Packard Enterprise Development LP.
 * Copyright (c) 2025 VDURA, Inc.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "mercury_event.h"

#include "mercury_util_error.h"

/*---------------------------------------------------------------------------*/
int
hg_event_create(void)
{
    int fd = -1;
#if defined(_WIN32)
    HG_UTIL_GOTO_ERROR(done, fd, -1, "Not implemented");
#elif defined(HG_UTIL_HAS_SYSEVENTFD_H)
    /* Create local signal event on self address */
    fd = eventfd(0, EFD_NONBLOCK | EFD_SEMAPHORE);
    HG_UTIL_CHECK_ERROR_NORET(
        fd == -1, done, "eventfd() failed (%s)", strerror(errno));
#elif defined(HG_UTIL_HAS_SYSEVENT_H)
    struct kevent kev;
    int rc;

    /* Create kqueue */
    fd = kqueue();
    HG_UTIL_CHECK_ERROR_NORET(
        fd == -1, done, "kqueue() failed (%s)", strerror(errno));

    EV_SET(&kev, HG_EVENT_IDENT, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, NULL);

    /* Add user-defined event to kqueue */
    rc = kevent(fd, &kev, 1, NULL, 0, NULL);
    HG_UTIL_CHECK_ERROR_NORET(
        rc == -1, error, "kevent() failed (%s)", strerror(errno));
#else

#endif
    HG_UTIL_LOG_DEBUG("Created event fd=%d", fd);

done:
    return fd;

#if defined(HG_UTIL_HAS_SYSEVENT_H)
error:
    hg_event_destroy(fd);

    return -1;
#endif
}

/*---------------------------------------------------------------------------*/
int
hg_event_destroy(int fd)
{
    int ret = HG_UTIL_SUCCESS;
#if defined(_WIN32)
    HG_UTIL_GOTO_ERROR(done, ret, HG_UTIL_FAIL, "Not implemented");
#else
    int rc = close(fd);
    HG_UTIL_CHECK_ERROR(rc == -1, done, ret, HG_UTIL_FAIL,
        "close() failed (%s)", strerror(errno));
#endif
    HG_UTIL_LOG_DEBUG("Destroyed event fd=%d", fd);

done:
    return ret;
}
